package com.psp.web.controller.springmvc;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;


public class Test {

	public static void main(String[] args) {

		List<Model> models = new ArrayList<>();
		for (int i = 1; i <= 20; i++) {
			Model m = new Model();
			m.id = i;
			m.name = "name" + i;
			if (i < 5) {
				m.gid = 1;
				m.gname = "gname" + 1;
			} else if (i < 12) {
				m.gid = 2;
				m.gname = "gname" + 2;
			} else {
				m.gid = 3;
				m.gname = "gname" + 3;
			}
			models.add(m);
		}

		// 进行分组

		Set<Model> set = new HashSet<>();
		set.addAll(models); // 将list中的值加入set,并去掉重复
		List<ModelGroup> groups = new ArrayList<>();
		for (Iterator<Model> it = set.iterator(); it.hasNext();) {
			ModelGroup g = new ModelGroup();
			Model model = (Model) it.next();
			g.setGid(model.getGid());
			g.setGname(model.getGname());
			List<Model> children = new ArrayList<>();
			for(Model m : models){
				if(m.getGid() == g.getGid()) {
					children.add(m);
				}
				g.setModels(children);
			}
			groups.add(g);
		}
	}

	static class Model {
		int id;
		String name;
		int gid;
		String gname;

		public int getId() {
			return id;
		}

		public void setId(int id) {
			this.id = id;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public int getGid() {
			return gid;
		}

		public void setGid(int gid) {
			this.gid = gid;
		}

		public String getGname() {
			return gname;
		}

		public void setGname(String gname) {
			this.gname = gname;
		}

		public boolean equals(Object obj) {
			if (obj == null)
				return false;
			if (this == obj)
				return true;
			if (obj instanceof Model) {
				Model model = (Model) obj;
				if (model.gid == this.gid && model.gname.equals(this.gname))
					return true;
			}
			return false;
		}
		
		 @Override  
	    public int hashCode() {  
	        return gid * gname.hashCode();  
	    }  

	}

	static class ModelGroup {
		int gid;
		String gname;

		public int getGid() {
			return gid;
		}

		public void setGid(int gid) {
			this.gid = gid;
		}

		public String getGname() {
			return gname;
		}

		public void setGname(String gname) {
			this.gname = gname;
		}

		public List<Model> getModels() {
			return models;
		}

		public void setModels(List<Model> models) {
			this.models = models;
		}

		List<Model> models;
	}
}
